import {
  EditOutlined,
  EyeOutlined,
  KeyOutlined,
  PlusOutlined,
  SwapOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Switch,
  Table,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import './index.less';
import { change_table, getTable, miss_table,add_table,get_zhiquan} from './api';

const onFish =() =>{

}

const LawyerList: React.FC = () => {
  const [isReadOnly, setIsReadOnly] = useState(true);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<any>(null);
  const [form] = Form.useForm();
  
  //从后端拿取表格
  const [lawyers, setLawyers] = useState([]);
  const fetchData = async () => {
    try {
      // 传入分页参数（第 1 页，每页 10 条）
      const response = await getTable({ 
        page: 1, 
        pageSize: 10, 
      });
      setLawyers(response.data)
  }
  catch (error) {
      console.error('获取数据失败', error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // 处理新增律师
  const handleAddLawyer = () => {
    setEditingRecord(null);
    form.resetFields();
    setIsModalVisible(true);
    setIsReadOnly(false)
  };

  // 处理编辑律师
  const handleEditLawyer = (record: any) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
    setIsReadOnly(false)
  };

  // 处理查看律师
  const handleViewLawyer = (record: any) => {
    message.info(`查看律师: ${record.name}`);
    form.setFieldsValue(record);
    setIsModalVisible(true);
    setIsReadOnly(true)
  };

  // 处理重置密码
  const handleResetPassword = (record: any) => {
    
  };

  // 处理删除律师
  const handleTransferWork = async (id: number) => {
  try {
    const response = await miss_table({ id: id });
      message.success('删除成功');
      fetchData();
    
  } catch (error) {
    message.error('删除失败');
  }
};


  // 处理账号状态切换
  const handleStatusChange = (checked: boolean, record: any) => {
    Modal.confirm({
      title: '确认状态变更',
      content: `确定要${checked ? '启用' : '禁用'}律师 ${record.name} 的账号吗？`,
      onOk: () => {
        message.success(`账号已${checked ? '启用' : '禁用'}`);
      },
      onCancel:()=>{

        message.success('已取消');
      }
    });
  };

  // 处理表单提交
  const handleFormSubmit = async () => {
    
  };

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      align: 'center',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 150,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
    },
    {
      title: '账号状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      align: 'center',
      render: (status: boolean, record: any) => (
        <Switch
          checked={status}
          onChange={(checked) => handleStatusChange(checked, record)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            size="small"
            icon={<KeyOutlined />}
            onClick={() => handleResetPassword(record)}
          >
            重置密码
          </Button>
          <span>|</span>
          <Button
            type="link"
            size="small"
            icon={<SwapOutlined />}
            onClick={() => handleTransferWork(record)}
          >
            删除
          </Button>
          <span>|</span>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditLawyer(record)}
          >
            编辑
          </Button>
          <span>|</span>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewLawyer(record)}
          >
            查看
          </Button>
        </Space>
      ),
    },
  ];

  

  return (
    <div className="lawyer-list">
      <Card>
        <div className="add-button-container">
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddLawyer}>
            新增律师
          </Button>
        </div>

        <Table
         rowKey="id"
          columns={columns}
          dataSource={lawyers}
          pagination={{
            total: 3,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条数据`,
          }}
          scroll={{ x: 'max-content' }}
        />
      </Card>

      {/* 弹窗 */}
      <Modal
        open={isModalVisible}
        onOk={handleFormSubmit}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        width={600}
      >
        <Form
        onFinish={onFish}
          form={form}
          layout="vertical"
          initialValues={{
            status: true,
            role: '负责律师',
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                 
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" readOnly={isReadOnly}/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" readOnly={isReadOnly}/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="role"
                label="角色"
                rules={[{ required: true, message: '请选择角色' }]}
              >
                <Select placeholder="请选择角色"
                disabled={isReadOnly} >
                  <Select.Option value="负责律师" id="1">负责律师</Select.Option>
                  <Select.Option value="主办律师" id="2">主办律师</Select.Option>
                  <Select.Option value="助理律师" id="3">助理律师</Select.Option>
                </Select>
              </Form.Item>
               <Col span={12}>
              <Form.Item
                name="zhiquan"
                label="职权"
                rules={[{ required: true, message: '角色对应职权' }]}
              >
                <Input placeholder="请先选择角色" readOnly={true} />
              
              </Form.Item>
            </Col>
            </Col>
            <Col span={12}>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="账号状态" valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" disabled={isReadOnly} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default LawyerList;
